#include "sqlite_manager.h"
#include "../config/cabrillo_config.h"
#include <iostream>
#include <sstream>
#include <cstring>

SQLiteManager::SQLiteManager() : db_(nullptr) {}

SQLiteManager::~SQLiteManager() {
    disconnect();
}

SQLiteManager& SQLiteManager::getInstance() {
    static SQLiteManager instance;
    return instance;
}

bool SQLiteManager::connect(const std::string& db_path) {
        // 获取默认的QSO类型（从Cabrillo配置中获取）
    CabrilloConfig* cabrilloConfig = CabrilloConfig::getInstance();
    std::string defaultDBName = cabrilloConfig->get("CabrilloConfig.DBNAME", db_path);
    

    db_path_ = defaultDBName;
    std::cout << "打开数据库：" << defaultDBName << std::endl;
    int rc = sqlite3_open(defaultDBName.c_str(), &db_);
    if (rc) {
        std::cerr << "无法打开数据库: " << sqlite3_errmsg(db_) << std::endl;
        return false;
    }
    
    return initializeDatabase();
}

void SQLiteManager::disconnect() {
    if (db_) {
        sqlite3_close(db_);
        db_ = nullptr;
    }
}

bool SQLiteManager::initializeDatabase() {
    // 创建QSO表
    const char* create_qso_table = R"(
        CREATE TABLE IF NOT EXISTS qso_records (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            date TEXT NOT NULL,
            time TEXT NOT NULL,
            callsign TEXT NOT NULL,
            band TEXT NOT NULL,
            frequency TEXT NOT NULL,
            mode TEXT NOT NULL,
            rst_sent TEXT NOT NULL,
            rst_rcvd TEXT NOT NULL,
            exch1 TEXT  NOT NULL DEFAULT '',
            exch2 TEXT  NOT NULL DEFAULT '',
            myexch1 TEXT  NOT NULL DEFAULT '',
            myexch2 TEXT  NOT NULL DEFAULT '',
            name TEXT,
            qth TEXT,
            memo TEXT,
            data TEXT,
            log_creation_date DATETIME,
            record_create_time DATETIME,
            record_modify_time DATETIME
        );
    )";
    
    // 创建JSON存储表
    const char* create_json_table = R"(
        CREATE TABLE IF NOT EXISTS json_data (
            key TEXT PRIMARY KEY,
            json_value TEXT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        );
    )";
    
    char* errMsg = 0;
    int rc;
    
    // 创建QSO表
    rc = sqlite3_exec(db_, create_qso_table, 0, 0, &errMsg);
    if (rc != SQLITE_OK) {
        std::cerr << "创建QSO表失败: " << errMsg << std::endl;
        sqlite3_free(errMsg);
        return false;
    }
    
    // 创建JSON表
    rc = sqlite3_exec(db_, create_json_table, 0, 0, &errMsg);
    if (rc != SQLITE_OK) {
        std::cerr << "创建JSON表失败: " << errMsg << std::endl;
        sqlite3_free(errMsg);
        return false;
    }
    
    return true;
}

std::string SQLiteManager::escapeString(const std::string& str) {
    // 更全面的字符串转义处理
    std::string result;
    for (char c : str) {
        switch (c) {
            case '\'':
                result += "''";  // SQL中单引号的转义是用两个单引号
                break;
            case '\"':
                result += "\\\"";  // 双引号转义
                break;
            case '\\':
                result += "\\\\";  // 反斜杠转义
                break;
            case '\n':
                result += "\\n";   // 换行符转义
                break;
            case '\r':
                result += "\\r";   // 回车符转义
                break;
            case '\t':
                result += "\\t";   // 制表符转义
                break;
            case '\b':
                result += "\\b";   // 退格符转义
                break;
            case '\f':
                result += "\\f";   // 换页符转义
                break;
            default:
                // 过滤掉非打印字符（ASCII值小于32且不是上述特殊字符）
                if (static_cast<unsigned char>(c) >= 32 || c == ' ') {
                    result += c;
                }
                break;
        }
    }
    return result;
}

std::string SQLiteManager::cleanString(const std::string& str) {
    // 清理字符串中的异常字符
    std::string result;
    for (char c : str) {
        // 只保留可打印字符和常见的空白字符
        if ((static_cast<unsigned char>(c) >= 32 && static_cast<unsigned char>(c) <= 126) || 
            c == ' ' || c == '\t' || c == '\n' || c == '\r') {
            result += c;
        }
        // 或者替换异常字符为问号
        // else {
        //     result += '?';
        // }
    }
    return result;
}

bool SQLiteManager::insertQSO(const QSORecord& record) {
    if (!db_) {
        std::cerr << "数据库未连接" << std::endl;
        return false;
    }
    
    std::stringstream sql;
    sql << "INSERT INTO qso_records (date, time, callsign, band, frequency, mode, rst_sent, rst_rcvd,exch1,exch2,myexch1,myexch2, name, qth, memo, data, log_creation_date, record_create_time, record_modify_time) VALUES ("
        << "'" << escapeString(record.date) << "', "
        << "'" << escapeString(record.time) << "', "
        << "'" << escapeString(record.callsign) << "', "
        << "'" << escapeString(record.band) << "', "
        << "'" << escapeString(record.frequency) << "', "
        << "'" << escapeString(record.mode) << "', "
        << "'" << escapeString(record.rst_sent) << "', "
        << "'" << escapeString(record.rst_rcvd) << "', "
        << "'" << escapeString(record.exch1) << "', "
        << "'" << escapeString(record.exch2) << "', "
        << "'" << escapeString(record.myexch1) << "', "
        << "'" << escapeString(record.myexch2) << "', "
        << "'" << escapeString(record.name) << "', "
        << "'" << escapeString(record.qth) << "', "
        << "'" << escapeString(record.memo) << "', "
        << "'" << escapeString(record.data) << "', "
        << "'" << escapeString(record.log_creation_date) << "', "
        << "'" << escapeString(record.record_create_time) << "', "
        << "'" << escapeString(record.record_modify_time) << "');";
    
    char* errMsg = 0;
    int rc = sqlite3_exec(db_, sql.str().c_str(), 0, 0, &errMsg);
    
    if (rc != SQLITE_OK) {
        std::cerr << "插入QSO记录失败: " << errMsg << std::endl;
        sqlite3_free(errMsg);
        return false;
    }
    
    return true;
}

bool SQLiteManager::updateQSO(const QSORecord& record) {
    if (!db_) {
        std::cerr << "数据库未连接" << std::endl;
        return false;
    }
    
    std::stringstream sql;
    sql << "UPDATE qso_records SET "
        << "date = '" << escapeString(record.date) << "', "
        << "time = '" << escapeString(record.time) << "', "
        << "callsign = '" << escapeString(record.callsign) << "', "
        << "band = '" << escapeString(record.band) << "', "
        << "frequency = '" << escapeString(record.frequency) << "', "
        << "mode = '" << escapeString(record.mode) << "', "
        << "rst_sent = '" << escapeString(record.rst_sent) << "', "
        << "rst_rcvd = '" << escapeString(record.rst_rcvd) << "', "
        << "exch1 = '" << escapeString(record.exch1) << "', "
        << "exch2 = '" << escapeString(record.exch2) << "', "
        << "myexch1 = '" << escapeString(record.myexch1) << "', "
        << "myexch2 = '" << escapeString(record.myexch2) << "', "
        << "name = '" << escapeString(record.name) << "', "
        << "qth = '" << escapeString(record.qth) << "', "
        << "memo = '" << escapeString(record.memo) << "', "
        << "data = '" << escapeString(record.data) << "', "
        << "log_creation_date = '" << escapeString(record.log_creation_date) << "', "
        << "record_create_time = '" << escapeString(record.record_create_time) << "', "
        << "record_modify_time = '" << escapeString(record.record_modify_time) << "' "
        << "WHERE id = " << record.id << ";";
    
    char* errMsg = 0;
    int rc = sqlite3_exec(db_, sql.str().c_str(), 0, 0, &errMsg);
    
    if (rc != SQLITE_OK) {
        std::cerr << "更新QSO记录失败: " << errMsg << std::endl;
        sqlite3_free(errMsg);
        return false;
    }
    
    return true;
}

bool SQLiteManager::deleteQSO(const std::string& id) {
    if (!db_) {
        std::cerr << "数据库未连接" << std::endl;
        return false;
    }
    
    std::stringstream sql;
    sql << "DELETE FROM qso_records WHERE id = " << id << ";";
    
    char* errMsg = 0;
    int rc = sqlite3_exec(db_, sql.str().c_str(), 0, 0, &errMsg);
    
    if (rc != SQLITE_OK) {
        std::cerr << "删除QSO记录失败: " << errMsg << std::endl;
        sqlite3_free(errMsg);
        return false;
    }
    
    return true;
}
bool SQLiteManager::setDataFieldValue(const std::string& id, const std::string& field, const std::string& value) {
    if (!db_) {
        std::cerr << "数据库未连接" << std::endl;
        return false;
    }
    //-- 为ID=15的记录的JSON字段添加must_send_QSL属性为1
    std::stringstream sql;
    //SET data = json_set(data, '$.must_send_QSL', 1)
    sql << "UPDATE qso_records SET data = json_set(data, '$." << field <<"', '" << value << "') "
        << "WHERE id = " << id << ";";
    
    char* errMsg = 0;
    int rc = sqlite3_exec(db_, sql.str().c_str(), 0, 0, &errMsg);
    std::cout << "更新字段" << field << "值: " << value << std::endl;
    if (rc != SQLITE_OK) {
        std::cerr << "更新字段" << field << "值失败: " << errMsg << std::endl;
        sqlite3_free(errMsg);
        return false;
    }
    
    return true;
}
std::vector<QSORecord> SQLiteManager::getAllQSOs() {
    std::vector<QSORecord> records;
    
    if (!db_) {
        std::cerr << "数据库未连接" << std::endl;
        return records;
    }
    
    const char* sql = "SELECT id, date, time, callsign, band, frequency, mode, rst_sent, rst_rcvd, exch1, exch2, myexch1, myexch2, name, qth, memo, data, log_creation_date, record_create_time, record_modify_time FROM qso_records ORDER BY date DESC, time DESC;";
    sqlite3_stmt* stmt;
    int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, NULL);
    
    if (rc != SQLITE_OK) {
        std::cerr << "查询QSO记录失败: " << sqlite3_errmsg(db_) << std::endl;
        return records;
    }
    
    while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
        QSORecord record;
        record.id = std::to_string(sqlite3_column_int(stmt, 0));
        record.date = (char*)sqlite3_column_text(stmt, 1);
        record.time = (char*)sqlite3_column_text(stmt, 2);
        record.callsign = (char*)sqlite3_column_text(stmt, 3);
        record.band = (char*)sqlite3_column_text(stmt, 4);
        record.frequency = (char*)sqlite3_column_text(stmt, 5);
        record.mode = (char*)sqlite3_column_text(stmt, 6);
        record.rst_sent = (char*)sqlite3_column_text(stmt, 7);
        record.rst_rcvd = (char*)sqlite3_column_text(stmt, 8);
        record.exch1 = (char*)sqlite3_column_text(stmt, 9);
        record.exch2 = (char*)sqlite3_column_text(stmt, 10);
        record.myexch1 = (char*)sqlite3_column_text(stmt, 11);
        record.myexch2 = (char*)sqlite3_column_text(stmt, 12);
        record.name = (char*)sqlite3_column_text(stmt, 13);
        record.qth = (char*)sqlite3_column_text(stmt, 14);
        record.memo = cleanString((char*)sqlite3_column_text(stmt, 15));
        record.data = (char*)sqlite3_column_text(stmt, 16);
        record.log_creation_date = (char*)sqlite3_column_text(stmt, 17);
        record.record_create_time = (char*)sqlite3_column_text(stmt, 18);
        record.record_modify_time = (char*)sqlite3_column_text(stmt, 19);
        
        records.push_back(record);
    }
    
    sqlite3_finalize(stmt);
    return records;
}

std::vector<QSORecord> SQLiteManager::getAllQSOs(int page, int pageSize, int& totalCount) {
    std::vector<QSORecord> records;
    
    if (!db_) {
        std::cerr << "数据库未连接" << std::endl;
        return records;
    }
    
    // 首先获取总记录数
    const char* countSql = "SELECT COUNT(*) FROM qso_records;";
    sqlite3_stmt* countStmt;
    int rc = sqlite3_prepare_v2(db_, countSql, -1, &countStmt, NULL);
    
    if (rc != SQLITE_OK) {
        std::cerr << "查询QSO记录总数失败: " << sqlite3_errmsg(db_) << std::endl;
        return records;
    }
    
    if ((rc = sqlite3_step(countStmt)) == SQLITE_ROW) {
        totalCount = sqlite3_column_int(countStmt, 0);
    }
    sqlite3_finalize(countStmt);
    
    // 计算偏移量
    int offset = (page - 1) * pageSize;
    
    // 查询当前页的数据
    std::stringstream sql;
    sql << "SELECT id, date, time, callsign, band, frequency, mode, rst_sent, rst_rcvd, exch1, exch2, myexch1, myexch2, name, qth, memo, data, log_creation_date, record_create_time, record_modify_time FROM qso_records ORDER BY date DESC, time DESC LIMIT " << pageSize << " OFFSET " << offset << ";";
    
    sqlite3_stmt* stmt;
    rc = sqlite3_prepare_v2(db_, sql.str().c_str(), -1, &stmt, NULL);
    
    if (rc != SQLITE_OK) {
        std::cerr << "查询QSO记录失败: " << sqlite3_errmsg(db_) << std::endl;
        return records;
    }
    
    while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
        QSORecord record;
        record.id = std::to_string(sqlite3_column_int(stmt, 0));
        record.date = (char*)sqlite3_column_text(stmt, 1);
        record.time = (char*)sqlite3_column_text(stmt, 2);
        record.callsign = (char*)sqlite3_column_text(stmt, 3);
        record.band = (char*)sqlite3_column_text(stmt, 4);
        record.frequency = (char*)sqlite3_column_text(stmt, 5);
        record.mode = (char*)sqlite3_column_text(stmt, 6);
        record.rst_sent = (char*)sqlite3_column_text(stmt, 7);
        record.rst_rcvd = (char*)sqlite3_column_text(stmt, 8);
        record.exch1 = (char*)sqlite3_column_text(stmt, 9);
        record.exch2 = (char*)sqlite3_column_text(stmt, 10);
        record.myexch1 = (char*)sqlite3_column_text(stmt, 11);
        record.myexch2 = (char*)sqlite3_column_text(stmt, 12);
        record.name = (char*)sqlite3_column_text(stmt, 13);
        record.qth = (char*)sqlite3_column_text(stmt, 14);
        record.memo = cleanString((char*)sqlite3_column_text(stmt, 15));
        record.data = (char*)sqlite3_column_text(stmt, 16);
        record.log_creation_date = (char*)sqlite3_column_text(stmt, 17);
        record.record_create_time = (char*)sqlite3_column_text(stmt, 18);
        record.record_modify_time = (char*)sqlite3_column_text(stmt, 19);
        
        records.push_back(record);
    }
    
    sqlite3_finalize(stmt);
    return records;
}

std::vector<QSORecord> SQLiteManager::getQSOsByCallsign(const std::string& callsignPrefix) {
    std::vector<QSORecord> records;
    
    if (!db_) {
        std::cerr << "数据库未连接" << std::endl;
        return records;
    }
    
    // 构造带筛选条件的SQL查询
    std::stringstream sql;
    sql << "SELECT id, date, time, callsign, band, frequency, mode, rst_sent, rst_rcvd, exch1, exch2, myexch1, myexch2, name, qth, memo, data, log_creation_date, record_create_time, record_modify_time FROM qso_records WHERE callsign LIKE '" << escapeString(callsignPrefix) << "%' ORDER BY date DESC, time DESC;";
    
    sqlite3_stmt* stmt;
    int rc = sqlite3_prepare_v2(db_, sql.str().c_str(), -1, &stmt, NULL);
    
    if (rc != SQLITE_OK) {
        std::cerr << "查询QSO记录失败: " << sqlite3_errmsg(db_) << std::endl;
        return records;
    }
    
    while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
        QSORecord record;
        record.id = std::to_string(sqlite3_column_int(stmt, 0));
        record.date = (char*)sqlite3_column_text(stmt, 1);
        record.time = (char*)sqlite3_column_text(stmt, 2);
        record.callsign = (char*)sqlite3_column_text(stmt, 3);
        record.band = (char*)sqlite3_column_text(stmt, 4);
        record.frequency = (char*)sqlite3_column_text(stmt, 5);
        record.mode = (char*)sqlite3_column_text(stmt, 6);
        record.rst_sent = (char*)sqlite3_column_text(stmt, 7);
        record.rst_rcvd = (char*)sqlite3_column_text(stmt, 8);
        record.exch1 = (char*)sqlite3_column_text(stmt, 9);
        record.exch2 = (char*)sqlite3_column_text(stmt, 10);
        record.myexch1 = (char*)sqlite3_column_text(stmt, 11);
        record.myexch2 = (char*)sqlite3_column_text(stmt, 12);
        record.name = (char*)sqlite3_column_text(stmt, 13);
        record.qth = (char*)sqlite3_column_text(stmt, 14);
        record.memo = cleanString((char*)sqlite3_column_text(stmt, 15));
        record.data = (char*)sqlite3_column_text(stmt, 16);
        record.log_creation_date = (char*)sqlite3_column_text(stmt, 17);
        record.record_create_time = (char*)sqlite3_column_text(stmt, 18);
        record.record_modify_time = (char*)sqlite3_column_text(stmt, 19);
        
        records.push_back(record);
    }
    
    sqlite3_finalize(stmt);
    return records;
}

std::vector<QSORecord> SQLiteManager::getQSOsByCallsign(const std::string& callsignPrefix, int page, int pageSize, int& totalCount) {
    std::vector<QSORecord> records;
    
    if (!db_) {
        std::cerr << "数据库未连接" << std::endl;
        return records;
    }
    
    // 首先获取符合条件的总记录数
    std::stringstream countSql;
    countSql << "SELECT COUNT(*) FROM qso_records WHERE callsign LIKE '" << escapeString(callsignPrefix) << "%';";
    sqlite3_stmt* countStmt;
    int rc = sqlite3_prepare_v2(db_, countSql.str().c_str(), -1, &countStmt, NULL);
    
    if (rc != SQLITE_OK) {
        std::cerr << "查询QSO记录总数失败: " << sqlite3_errmsg(db_) << std::endl;
        return records;
    }
    
    if ((rc = sqlite3_step(countStmt)) == SQLITE_ROW) {
        totalCount = sqlite3_column_int(countStmt, 0);
    }
    sqlite3_finalize(countStmt);
    
    // 如果总记录数为0，直接返回空结果
    if (totalCount == 0) {
        return records;
    }
    
    // 计算偏移量
    int offset = (page - 1) * pageSize;
    
    // 查询当前页的数据
    std::stringstream sql;
    sql << "SELECT id, date, time, callsign, band, frequency, mode, rst_sent, rst_rcvd, exch1, exch2, myexch1, myexch2, name, qth, memo, data, log_creation_date, record_create_time, record_modify_time FROM qso_records WHERE callsign LIKE '" << escapeString(callsignPrefix) << "%' ORDER BY date DESC, time DESC LIMIT " << pageSize << " OFFSET " << offset << ";";
    
    sqlite3_stmt* stmt;
    rc = sqlite3_prepare_v2(db_, sql.str().c_str(), -1, &stmt, NULL);
    
    if (rc != SQLITE_OK) {
        std::cerr << "查询QSO记录失败: " << sqlite3_errmsg(db_) << std::endl;
        return records;
    }
    
    while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
        QSORecord record;
        record.id = std::to_string(sqlite3_column_int(stmt, 0));
        record.date = (char*)sqlite3_column_text(stmt, 1);
        record.time = (char*)sqlite3_column_text(stmt, 2);
        record.callsign = (char*)sqlite3_column_text(stmt, 3);
        record.band = (char*)sqlite3_column_text(stmt, 4);
        record.frequency = (char*)sqlite3_column_text(stmt, 5);
        record.mode = (char*)sqlite3_column_text(stmt, 6);
        record.rst_sent = (char*)sqlite3_column_text(stmt, 7);
        record.rst_rcvd = (char*)sqlite3_column_text(stmt, 8);
        record.exch1 = (char*)sqlite3_column_text(stmt, 9);
        record.exch2 = (char*)sqlite3_column_text(stmt, 10);
        record.myexch1 = (char*)sqlite3_column_text(stmt, 11);
        record.myexch2 = (char*)sqlite3_column_text(stmt, 12);
        record.name = (char*)sqlite3_column_text(stmt, 13);
        record.qth = (char*)sqlite3_column_text(stmt, 14);
        record.memo = cleanString((char*)sqlite3_column_text(stmt, 15));
        record.data = (char*)sqlite3_column_text(stmt, 16);
        record.log_creation_date = (char*)sqlite3_column_text(stmt, 17);
        record.record_create_time = (char*)sqlite3_column_text(stmt, 18);
        record.record_modify_time = (char*)sqlite3_column_text(stmt, 19);
        
        records.push_back(record);
    }
    
    sqlite3_finalize(stmt);
    return records;
}

QSORecord SQLiteManager::getQSOById(const std::string& id) {
    QSORecord record;
    
    if (!db_) {
        std::cerr << "数据库未连接" << std::endl;
        return record;
    }
    
    std::stringstream sql;
    sql << "SELECT id, date, time, callsign, band, frequency, mode, rst_sent, rst_rcvd, exch1, exch2, myexch1, myexch2, name, qth, memo, data, log_creation_date, record_create_time, record_modify_time FROM qso_records WHERE id = " << id << ";";
    
    sqlite3_stmt* stmt;
    int rc = sqlite3_prepare_v2(db_, sql.str().c_str(), -1, &stmt, NULL);
    
    if (rc != SQLITE_OK) {
        std::cerr << "查询QSO记录失败: " << sqlite3_errmsg(db_) << std::endl;
        return record;
    }
    
    if ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
        record.id = std::to_string(sqlite3_column_int(stmt, 0));
        record.date = (char*)sqlite3_column_text(stmt, 1);
        record.time = (char*)sqlite3_column_text(stmt, 2);
        record.callsign = (char*)sqlite3_column_text(stmt, 3);
        record.band = (char*)sqlite3_column_text(stmt, 4);
        record.frequency = (char*)sqlite3_column_text(stmt, 5);
        record.mode = (char*)sqlite3_column_text(stmt, 6);
        record.rst_sent = (char*)sqlite3_column_text(stmt, 7);
        record.rst_rcvd = (char*)sqlite3_column_text(stmt, 8);
        record.exch1 = (char*)sqlite3_column_text(stmt, 9);
        record.exch2 = (char*)sqlite3_column_text(stmt, 10);
        record.myexch1 = (char*)sqlite3_column_text(stmt, 11);
        record.myexch2 = (char*)sqlite3_column_text(stmt, 12);
        record.name = (char*)sqlite3_column_text(stmt, 13);
        record.qth = (char*)sqlite3_column_text(stmt, 14);
        record.memo = cleanString((char*)sqlite3_column_text(stmt, 15));
        record.data = (char*)sqlite3_column_text(stmt, 16);
        record.log_creation_date = (char*)sqlite3_column_text(stmt, 17);
        record.record_create_time = (char*)sqlite3_column_text(stmt, 18);
        record.record_modify_time = (char*)sqlite3_column_text(stmt, 19);
    }
    
    sqlite3_finalize(stmt);
    return record;
}

bool SQLiteManager::saveJSON(const std::string& key, const std::string& json_data) {
    if (!db_) {
        std::cerr << "数据库未连接" << std::endl;
        return false;
    }
    
    std::stringstream sql;
    sql << "INSERT OR REPLACE INTO json_data (key, json_value, updated_at) VALUES ("
        << "'" << escapeString(key) << "', "
        << "'" << escapeString(json_data) << "', "
        << "CURRENT_TIMESTAMP);";
    
    char* errMsg = 0;
    int rc = sqlite3_exec(db_, sql.str().c_str(), 0, 0, &errMsg);
    
    if (rc != SQLITE_OK) {
        std::cerr << "保存JSON数据失败: " << errMsg << std::endl;
        sqlite3_free(errMsg);
        return false;
    }
    
    return true;
}

std::string SQLiteManager::loadJSON(const std::string& key) {
    if (!db_) {
        std::cerr << "数据库未连接" << std::endl;
        return "";
    }
    
    std::stringstream sql;
    sql << "SELECT json_value FROM json_data WHERE key = '" << escapeString(key) << "';";
    
    sqlite3_stmt* stmt;
    int rc = sqlite3_prepare_v2(db_, sql.str().c_str(), -1, &stmt, NULL);
    
    if (rc != SQLITE_OK) {
        std::cerr << "查询JSON数据失败: " << sqlite3_errmsg(db_) << std::endl;
        return "";
    }
    
    std::string result = "";
    if ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
        result = (char*)sqlite3_column_text(stmt, 0);
    }
    
    sqlite3_finalize(stmt);
    return result;
}

bool SQLiteManager::deleteJSON(const std::string& key) {
    if (!db_) {
        std::cerr << "数据库未连接" << std::endl;
        return false;
    }
    
    std::stringstream sql;
    sql << "DELETE FROM json_data WHERE key = '" << escapeString(key) << "';";
    
    char* errMsg = 0;
    int rc = sqlite3_exec(db_, sql.str().c_str(), 0, 0, &errMsg);
    
    if (rc != SQLITE_OK) {
        std::cerr << "删除JSON数据失败: " << errMsg << std::endl;
        sqlite3_free(errMsg);
        return false;
    }
    
    return true;
}